package com.bw.interceptor;

import com.bw.common.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 浏览器自动发来的cookie
        Cookie[] cookies = request.getCookies();

        boolean flag = false; // 默认校验不通过
        if (cookies != null) {
            //过滤 从众多cookie中 找到 token令牌
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("token".equals(name)) {
                    String token = cookie.getValue();
                    flag = JwtUtils.validToken(token);
                }
            }
        }


        if (!flag) { // 如果验证不通过  则去登录
            response.sendRedirect("/loginPage.do");
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
